home *** CD-ROM | disk | FTP | other *** search
/ Programming a Multiplayer FPS in DirectX / Programming a Multiplayer FPS in DirectX (Companion CD).iso / Source / Chapter 5 / Engine / Engine.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2005-03-29  |  12.8 KB  |  399 lines

  1. //-----------------------------------------------------------------------------
  2. // Engine.h implementation.
  3. // Refer to the Engine.h interface for more details.
  4. //
  5. // Programming a Multiplayer First Person Shooter in DirectX
  6. // Copyright (c) 2004 Vaughan Young
  7. //-----------------------------------------------------------------------------
  8. #include "Engine.h"
  9.  
  10. //-----------------------------------------------------------------------------
  11. // Globals
  12. //-----------------------------------------------------------------------------
  13. Engine *g_engine = NULL;
  14.  
  15. //-----------------------------------------------------------------------------
  16. // Handles Windows messages.
  17. //-----------------------------------------------------------------------------
  18. LRESULT CALLBACK WindowProc( HWND wnd, UINT msg, WPARAM wparam, LPARAM lparam )
  19. {
  20.     switch( msg )
  21.     {
  22.         case WM_ACTIVATEAPP:
  23.             g_engine->SetDeactiveFlag( !wparam );
  24.             return 0;
  25.  
  26.         case WM_DESTROY:
  27.             PostQuitMessage( 0 );
  28.             return 0;
  29.  
  30.         default:
  31.             return DefWindowProc( wnd, msg, wparam, lparam );
  32.     }
  33. }
  34.  
  35. //-----------------------------------------------------------------------------
  36. // The engine class constructor.
  37. //-----------------------------------------------------------------------------
  38. Engine::Engine( EngineSetup *setup )
  39. {
  40.     // Indicate that the engine is not yet loaded.
  41.     m_loaded = false;
  42.  
  43.     // If no setup structure was passed in, then create a default one.
  44.     // Otehrwise, make a copy of the passed in structure.
  45.     m_setup = new EngineSetup;
  46.     if( setup != NULL )
  47.         memcpy( m_setup, setup, sizeof( EngineSetup ) );
  48.  
  49.     // Store a pointer to the engine in a global variable for easy access.
  50.     g_engine = this;
  51.  
  52.     // Prepare and register the window class.
  53.     WNDCLASSEX wcex;
  54.     wcex.cbSize        = sizeof( WNDCLASSEX );
  55.     wcex.style         = CS_CLASSDC;
  56.     wcex.lpfnWndProc   = WindowProc;
  57.     wcex.cbClsExtra    = 0;
  58.     wcex.cbWndExtra    = 0;
  59.     wcex.hInstance     = m_setup->instance;
  60.     wcex.hIcon         = LoadIcon( NULL, IDI_APPLICATION );
  61.     wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );
  62.     wcex.hbrBackground = NULL;
  63.     wcex.lpszMenuName  = NULL;
  64.     wcex.lpszClassName = "WindowClass";
  65.     wcex.hIconSm       = LoadIcon( NULL, IDI_APPLICATION );
  66.     RegisterClassEx( &wcex );
  67.  
  68.     // Initialise the COM using multithreaded concurrency.
  69.     CoInitializeEx( NULL, COINIT_MULTITHREADED );
  70.  
  71.     // Create the Direct3D interface.
  72.     IDirect3D9 *d3d = Direct3DCreate9( D3D_SDK_VERSION );
  73.  
  74.     // Enumerate Direct3D device configurations on the default adapter.
  75.     g_deviceEnumeration = new DeviceEnumeration;
  76.     if( g_deviceEnumeration->Enumerate( d3d ) != IDOK )
  77.     {
  78.         SAFE_RELEASE( d3d );
  79.         return;
  80.     }
  81.  
  82.     // Create the window and retrieve a handle to it.
  83.     m_window = CreateWindow( "WindowClass", m_setup->name, g_deviceEnumeration->IsWindowed() ? WS_OVERLAPPED : WS_POPUP, 0, 0, 800, 600, NULL, NULL, m_setup->instance, NULL );
  84.  
  85.     // Prepare the device presentation parameters.
  86.     D3DPRESENT_PARAMETERS d3dpp;
  87.     ZeroMemory( &d3dpp, sizeof( D3DPRESENT_PARAMETERS ) );
  88.     d3dpp.BackBufferWidth = g_deviceEnumeration->GetSelectedDisplayMode()->Width;
  89.     d3dpp.BackBufferHeight = g_deviceEnumeration->GetSelectedDisplayMode()->Height;
  90.     d3dpp.BackBufferFormat = g_deviceEnumeration->GetSelectedDisplayMode()->Format;
  91.     d3dpp.BackBufferCount = m_setup->totalBackBuffers;
  92.     d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
  93.     d3dpp.hDeviceWindow = m_window;
  94.     d3dpp.Windowed = g_deviceEnumeration->IsWindowed();
  95.     d3dpp.EnableAutoDepthStencil = true;
  96.     d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
  97.     d3dpp.FullScreen_RefreshRateInHz = g_deviceEnumeration->GetSelectedDisplayMode()->RefreshRate;
  98.     if( g_deviceEnumeration->IsVSynced() == true )
  99.         d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
  100.     else
  101.         d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
  102.  
  103.     // Destroy the device enumeration object.
  104.     SAFE_DELETE( g_deviceEnumeration );
  105.  
  106.     // Create the Direct3D device.
  107.     if( FAILED( d3d->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, m_window, D3DCREATE_MIXED_VERTEXPROCESSING, &d3dpp, &m_device ) ) )
  108.         return;
  109.  
  110.     // Release the Direct3D interface as it is no longer needed.
  111.     SAFE_RELEASE( d3d );
  112.  
  113.     // Switch lighting off by default.
  114.     m_device->SetRenderState( D3DRS_LIGHTING, false );
  115.  
  116.     // Set the texture filters to use anisotropic texture filtering.
  117.     m_device->SetSamplerState ( 0, D3DSAMP_MAGFILTER, D3DTEXF_ANISOTROPIC );
  118.     m_device->SetSamplerState ( 0, D3DSAMP_MINFILTER, D3DTEXF_ANISOTROPIC );
  119.     m_device->SetSamplerState( 0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR );
  120.  
  121.     // Set the projection matrix.
  122.     D3DXMATRIX projMatrix;
  123.     D3DXMatrixPerspectiveFovLH( &projMatrix, D3DX_PI / 4, (float)d3dpp.BackBufferWidth / (float)d3dpp.BackBufferHeight, 0.1f / m_setup->scale, 1000.0f / m_setup->scale );
  124.     m_device->SetTransform( D3DTS_PROJECTION, &projMatrix );
  125.  
  126.     // Store the display mode details.
  127.     m_displayMode.Width = d3dpp.BackBufferWidth;
  128.     m_displayMode.Height = d3dpp.BackBufferHeight;
  129.     m_displayMode.RefreshRate = d3dpp.FullScreen_RefreshRateInHz;
  130.     m_displayMode.Format = d3dpp.BackBufferFormat;
  131.  
  132.     // The swap chain always starts on the first back buffer.
  133.     m_currentBackBuffer = 0;
  134.  
  135.     // Create the sprite interface.
  136.     D3DXCreateSprite( m_device, &m_sprite );
  137.  
  138.     // Create the linked lists of states.
  139.     m_states = new LinkedList< State >;
  140.     m_currentState = NULL;
  141.  
  142.     // Create the resource managers.
  143.     m_scriptManager = new ResourceManager< Script >;
  144.  
  145.     // Create the input object.
  146.     m_input = new Input( m_window );
  147.  
  148.     // Seed the random number generator with the current time.
  149.     srand( timeGetTime() );
  150.  
  151.     // Allow the application to perform any state setup now.
  152.     if( m_setup->StateSetup != NULL )
  153.         m_setup->StateSetup();
  154.  
  155.     // The engine is fully loaded and ready to go.
  156.     m_loaded = true;
  157. }
  158.  
  159. //-----------------------------------------------------------------------------
  160. // The engine class destructor.
  161. //-----------------------------------------------------------------------------
  162. Engine::~Engine()
  163. {
  164.     // Ensure the engine is loaded.
  165.     if( m_loaded == true )
  166.     {
  167.         // Destroy the states linked lists.
  168.         if( m_currentState != NULL )
  169.             m_currentState->Close();
  170.         SAFE_DELETE( m_states );
  171.  
  172.         // Destroy everything.
  173.         SAFE_DELETE( m_input );
  174.         SAFE_DELETE( m_scriptManager );
  175.  
  176.         // Release the sprite interface.
  177.         SAFE_RELEASE( m_sprite );
  178.  
  179.         // Release the device.
  180.         SAFE_RELEASE( m_device );
  181.     }
  182.  
  183.     // Uninitialise the COM.
  184.     CoUninitialize();
  185.  
  186.     // Unregister the window class.
  187.     UnregisterClass( "WindowClass", m_setup->instance );
  188.  
  189.     // Destroy the engine setup structure.
  190.     SAFE_DELETE( m_setup );
  191. }
  192.  
  193. //-----------------------------------------------------------------------------
  194. // Enters the engine into the main processing loop.
  195. //-----------------------------------------------------------------------------
  196. void Engine::Run()
  197. {
  198.     // Ensure the engine is loaded.
  199.     if( m_loaded == true )
  200.     {
  201.         // Show the window.
  202.         ShowWindow( m_window, SW_NORMAL );
  203.  
  204.         // Used to retrieve details about the viewer from the application.
  205.         ViewerSetup viewer;
  206.  
  207.         // Enter the message loop.
  208.         MSG msg;
  209.         ZeroMemory( &msg, sizeof( MSG ) );
  210.         while( msg.message != WM_QUIT )
  211.         {
  212.             if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
  213.             {
  214.                 TranslateMessage( &msg );
  215.                 DispatchMessage( &msg );
  216.             }
  217.             else if( !m_deactive )
  218.             {
  219.                 // Calculate the elapsed time.
  220.                 unsigned long currentTime = timeGetTime();
  221.                 static unsigned long lastTime = currentTime;
  222.                 float elapsed = ( currentTime - lastTime ) / 1000.0f;
  223.                 lastTime = currentTime;
  224.  
  225.                 // Update the input object, reading the keyboard and mouse.
  226.                 m_input->Update();
  227.  
  228.                 // Check if the user wants to make a forced exit.
  229.                 if( m_input->GetKeyPress( DIK_F1 ) )
  230.                     PostQuitMessage( 0 );
  231.  
  232.                 // Request the viewer from the current state, if there is one.
  233.                 if( m_currentState != NULL )
  234.                     m_currentState->RequestViewer( &viewer );
  235.  
  236.                 // Update the current state (if there is one), taking state
  237.                 // changes into account.
  238.                 m_stateChanged = false;
  239.                 if( m_currentState != NULL )
  240.                     m_currentState->Update( elapsed );
  241.                 if( m_stateChanged == true )
  242.                     continue;
  243.  
  244.                 // Begin the scene.
  245.                 m_device->Clear( 0, NULL, viewer.viewClearFlags, 0, 1.0f, 0 );
  246.                 if( SUCCEEDED( m_device->BeginScene() ) )
  247.                 {
  248.                     // Render the current state, if there is one.
  249.                     if( m_currentState != NULL )
  250.                         m_currentState->Render();
  251.  
  252.                     // End the scene and present it.
  253.                     m_device->EndScene();
  254.                     m_device->Present( NULL, NULL, NULL, NULL );
  255.  
  256.                     // Keep track of the index of the current back buffer.
  257.                     if( ++m_currentBackBuffer == m_setup->totalBackBuffers + 1 )
  258.                         m_currentBackBuffer = 0;
  259.                 }
  260.             }
  261.         }
  262.     }
  263.  
  264.     // Destroy the engine.
  265.     SAFE_DELETE( g_engine );
  266. }
  267.  
  268. //-----------------------------------------------------------------------------
  269. // Returns the window handle.
  270. //-----------------------------------------------------------------------------
  271. HWND Engine::GetWindow()
  272. {
  273.     return m_window;
  274. }
  275.  
  276. //-----------------------------------------------------------------------------
  277. // Sets the deactive flag.
  278. //-----------------------------------------------------------------------------
  279. void Engine::SetDeactiveFlag( bool deactive )
  280. {
  281.     m_deactive = deactive;
  282. }
  283.  
  284. //-----------------------------------------------------------------------------
  285. // Returns the scale that the engine is currently running in.
  286. //-----------------------------------------------------------------------------
  287. float Engine::GetScale()
  288. {
  289.     return m_setup->scale;
  290. }
  291.  
  292. //-----------------------------------------------------------------------------
  293. // Returns a pointer to the Direct3D device.
  294. //-----------------------------------------------------------------------------
  295. IDirect3DDevice9 *Engine::GetDevice()
  296. {
  297.     return m_device;
  298. }
  299.  
  300. //-----------------------------------------------------------------------------
  301. // Returns a pointer to the display mode of the current Direct3D device.
  302. //-----------------------------------------------------------------------------
  303. D3DDISPLAYMODE *Engine::GetDisplayMode()
  304. {
  305.     return &m_displayMode;
  306. }
  307.  
  308. //-----------------------------------------------------------------------------
  309. // Returns a pointer to the sprite interface.
  310. //-----------------------------------------------------------------------------
  311. ID3DXSprite *Engine::GetSprite()
  312. {
  313.     return m_sprite;
  314. }
  315.  
  316. //-----------------------------------------------------------------------------
  317. // Adds a state to the engine.
  318. //-----------------------------------------------------------------------------
  319. void Engine::AddState( State *state, bool change )
  320. {
  321.     m_states->Add( state );
  322.  
  323.     if( change == false )
  324.         return;
  325.  
  326.     if( m_currentState != NULL )
  327.         m_currentState->Close();
  328.  
  329.     m_currentState = m_states->GetLast();
  330.     m_currentState->Load();
  331. }
  332.  
  333. //-----------------------------------------------------------------------------
  334. // Removes a state from the engine
  335. //-----------------------------------------------------------------------------
  336. void Engine::RemoveState( State *state )
  337. {
  338.     m_states->Remove( &state );
  339. }
  340.  
  341. //-----------------------------------------------------------------------------
  342. // Changes processing to the state with the specified ID.
  343. //-----------------------------------------------------------------------------
  344. void Engine::ChangeState( unsigned long id )
  345. {
  346.     // Iterate through the list of states and find the new state to change to.
  347.     m_states->Iterate( true );
  348.     while( m_states->Iterate() != NULL )
  349.     {
  350.         if( m_states->GetCurrent()->GetID() == id )
  351.         {
  352.             // Close the old state.
  353.             if( m_currentState != NULL )
  354.                 m_currentState->Close();
  355.  
  356.             // Set the new current state and load it.
  357.             m_currentState = m_states->GetCurrent();
  358.             m_currentState->Load();
  359.  
  360.             // Swap the back buffers until the first one is in the front.
  361.             while( m_currentBackBuffer != 0 )
  362.             {
  363.                 m_device->Present( NULL, NULL, NULL, NULL );
  364.  
  365.                 if( ++m_currentBackBuffer == m_setup->totalBackBuffers + 1 )
  366.                     m_currentBackBuffer = 0;
  367.             }
  368.  
  369.             // Indicate that the state has changed.
  370.             m_stateChanged = true;
  371.  
  372.             break;
  373.         }
  374.     }
  375. }
  376.  
  377. //-----------------------------------------------------------------------------
  378. // Returns a pointer to the current state.
  379. //-----------------------------------------------------------------------------
  380. State *Engine::GetCurrentState()
  381. {
  382.     return m_currentState;
  383. }
  384.  
  385. //-----------------------------------------------------------------------------
  386. // Returns a pointer to the script manager.
  387. //-----------------------------------------------------------------------------
  388. ResourceManager< Script > *Engine::GetScriptManager()
  389. {
  390.     return m_scriptManager;
  391. }
  392.  
  393. //-----------------------------------------------------------------------------
  394. // Returns a pointer to the input object.
  395. //-----------------------------------------------------------------------------
  396. Input *Engine::GetInput()
  397. {
  398.     return m_input;
  399. }